﻿using UnityEngine;
using System.Collections.Generic;

public enum ROOMTYPES {
	STANDARD = 0,
	PANIC,
	PUZZLE,
	NUM_ROOMTYPES
}

public class GameManager : MonoBehaviour {

	public int numObjectives;
	public int completedObjectives;
	public ROOMTYPES roomType;

	public GameObject fireTile;

	Door _door;
	List<ROOMTYPES> _availableRooms;

	// Use this for initialization
	void Start () {
		DontDestroyOnLoad (this);

		completedObjectives = 0;
		_availableRooms = new List<ROOMTYPES> ();
		ReloadAvailableRooms ();

		GameObject door = GameObject.FindGameObjectWithTag ("Door");
		if (door != null) {
			_door = door.GetComponent<Door>();
		}
	}
	
	// Update is called once per frame
	void Update () {
		// If level objective is completed, open the door
		if (completedObjectives >= numObjectives && _door != null) {
			// open door
			_door.Open();
		}
	}

	public void LoadNextRoom() {
		int newRoomType = Random.Range(0, _availableRooms.Count);
		int levelNumber;

		roomType = _availableRooms [newRoomType];

		if (roomType == ROOMTYPES.STANDARD) {
			levelNumber = Random.Range(1, 4);
			Application.LoadLevel ("Room" + levelNumber);
		} else if (roomType == ROOMTYPES.PANIC) {
			levelNumber = Random.Range(1, 3);
			Application.LoadLevel ("PanicRoom" + levelNumber);
		} else if (roomType == ROOMTYPES.PUZZLE) {
			Application.LoadLevel("PuzzleRoom2");
		}

		_availableRooms.RemoveAt (newRoomType);
		if (_availableRooms.Count <= 0) {
			ReloadAvailableRooms();
		}
	}

	void ReloadAvailableRooms() {
		_availableRooms.Add (ROOMTYPES.STANDARD);
		_availableRooms.Add (ROOMTYPES.STANDARD);
		_availableRooms.Add (ROOMTYPES.PANIC);
		_availableRooms.Add (ROOMTYPES.PUZZLE);
	}

	void OnLevelWasLoaded(int level) {
		// Spawn whatever will be in the room
		if (roomType == ROOMTYPES.PANIC) {
			BuildPanicRoom();
		}

		_door = GameObject.FindGameObjectWithTag ("Door").GetComponent<Door>();
		
		numObjectives = DetermineNumObjectives ();
		completedObjectives = 0;
	}

	void BuildPanicRoom() {
		// Spawn a room of 14x8 fire tiles
		for(int i = 0; i < 14; ++i) {
			for(int j = 0; j < 8; ++j) {
				GameObject.Instantiate(fireTile, new Vector3(-232.0f + 35.6f*i, 132.0f - 37.6f*j, 1.0f), Quaternion.identity);
			}
		}
	}

	int DetermineNumObjectives() {
		int objectiveCount = 0;

		GameObject[] objectives = GameObject.FindGameObjectsWithTag ("Objective");
		foreach (GameObject objective in objectives) {
			if(objective.GetComponent<Objective>().isObjective) {
				++objectiveCount;
			}
		}

		/*
		GameObject[] tikis = GameObject.FindGameObjectsWithTag ("Tiki");
		foreach (GameObject tiki in tikis) {
			if(tiki.GetComponent<Objective>().isObjective) {
				++objectives;
			}
		}

		GameObject[] torches = GameObject.FindGameObjectsWithTag ("Torch");
		foreach (GameObject torch in torches) {
			if(torch.GetComponent<Objective>().isObjective) {
				++objectives;
			}
		}
		*/

		return objectiveCount;
	}
}
